package com.gzsxy.JUC.pool;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


//Executors 工具类  ：3大方法
//使用了线程池之后，使用线程池来创建线程
public class Demo01 {
    public static void main(String[] args) {
//        ExecutorService threadPool = Executors.newSingleThreadExecutor();//单个线程
//        ExecutorService threadPool = Executors.newFixedThreadPool(5); //创建一个固定的线程池大小
        ExecutorService threadPool = Executors.newCachedThreadPool(); //可伸缩的，遇强则强

        //总数是6 必须要执行任务的时候，再使用
        CountDownLatch countDownLatch = new CountDownLatch(6);

        try {
            for (int i = 0; i < 10; i++) {
                int temp = i;
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "ok" + temp);
                    //countDownLatch.countDown必须放在线程里面去执行
                    countDownLatch.countDown();
                });

            }

            countDownLatch.await();
            System.out.println("执行完成");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //线程池用完 要关闭线程池
            threadPool.shutdown();
        }
    }


}
